package com.example.ymm.modules1.service.impl.hl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.ymm.base.BaseServiceImpl;
import com.example.ymm.model.TableList;
import com.example.ymm.model.YmPageDto;
import com.example.ymm.modules1.entity.hl.dkn.DknItemPlan;
import com.example.ymm.modules1.entity.hl.dkn.DknMainPlan;
import com.example.ymm.modules1.entity.hl.dkn.DknPlanItem;
import com.example.ymm.modules1.mapper.hl.DknMainPlanMapper;
import com.example.ymm.modules1.query.hl.DknMainPlanQueryCriteria;
import com.example.ymm.modules1.service.hl.DknItemPlanService;
import com.example.ymm.modules1.service.hl.DknMainPlanService;
import com.example.ymm.modules1.service.hl.DknPlanItemService;
import com.example.ymm.util.DateKit;
import com.example.ymm.util.QueryHelpPlus;
import com.example.ymm.util.UtilValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@DSTransactional
@Slf4j
@DS("slave2")
public class DknMainPlanServiceImpl extends BaseServiceImpl<DknMainPlanMapper, DknMainPlan> implements DknMainPlanService {


    @Autowired
    DknItemPlanService dknItemPlanService;
    @Autowired
    DknPlanItemService dknPlanItemService;

    @Override
    public TableList<DknMainPlan> list(DknMainPlanQueryCriteria criteria, YmPageDto pageDto) {
        IPage<DknMainPlan> page = new Page<DknMainPlan>(pageDto.getPage(),pageDto.getPageSize());
        QueryWrapper predicate = QueryHelpPlus.getPredicate(DknMainPlan.class, criteria);
        predicate.orderByDesc("create_time");
        baseMapper.selectPage(page, predicate);
        TableList<DknMainPlan> tableList=new TableList(page);
        return tableList;
    }

    public List<DknMainPlan> queryAll(DknMainPlanQueryCriteria criteria) {
        QueryWrapper predicate = QueryHelpPlus.getPredicate(DknMainPlan.class, criteria);
//        predicate.orderByDesc("create_time");
        List<DknMainPlan> result =baseMapper.selectList(predicate);
        return result;
    }

    @Override
    public String productionPlanAdd(JSONObject jsonObject) {
        JSONArray orderNos = jsonObject.getJSONArray("selectOrderNo");
        JSONObject formData=jsonObject.getJSONObject("formData");
        JSONArray date_arr= formData.getJSONArray("date_rang");
        
        JSONArray planDateList = jsonObject.getJSONArray("planDateList");
        Map<String,String> map=new HashMap<String,String>();
        //防止重复
        orderNos.forEach(item->{
            map.put(item.toString(),(String)item);
        });
        List<String> orderNoList=new ArrayList<String>();
        map.entrySet().forEach(item->{
            orderNoList.add(item.getKey());
        });
        DknMainPlan dknMainPlan=new DknMainPlan();
        dknMainPlan.setUserId(getUserId());
        dknMainPlan.setUserName(getUserName());
        if(UtilValidate.isNotEmpty(date_arr)){
            dknMainPlan.setDateRangke(date_arr.getString(0)+"-"+date_arr.getString(1));
            dknMainPlan.setStartDate(DateKit.dateFormat(date_arr.getString(0)+" 00:00:00"));
            dknMainPlan.setEndDate(DateKit.dateFormat(date_arr.getString(1)+" 00:00:00"));
        }
        dknMainPlan.setBiaoShiNos(String.join(",",orderNoList));
        dknMainPlan.setTxtJson(jsonObject.toString());
        saveOrUpdate(dknMainPlan);

        /**
         * 存储订单标识号，排产的开始和结束时间
         */
        Map<String,String> start_map=new HashMap<>();//排产开始日期 key: 订单标识号，value: 日期
        Map<String,String> end_map=new HashMap<>();  //排产结束日期 key: 订单标识号，value: 日期
        Map<String,Integer> plan_map=new HashMap<>(); //日期是否排满 key: 日期  value：0 未满  1 已满
        for(int i=0;i<planDateList.size();i++){
            JSONObject item = planDateList.getJSONObject(i);
            String date=item.getString("date");
            JSONArray left_arr = item.getJSONArray("left_arr1");

            JSONArray arr1 = item.getJSONArray("arr1");
            JSONArray arr2 = item.getJSONArray("arr2");
            for(int j=0;j<arr1.size();j++){
                JSONObject item2 = arr1.getJSONObject(j);
                String biaoShiHao=item2.getString("biaoShiHao");
                if(start_map.containsKey(biaoShiHao)){
                }else{
                    start_map.put(biaoShiHao,date);
                }
                end_map.put(biaoShiHao,date);
            }
            for(int j=0;j<arr2.size();j++){
                JSONObject item2 = arr2.getJSONObject(j);
                String biaoShiHao=item2.getString("biaoShiHao");
                if(start_map.containsKey(biaoShiHao)){
                }else{
                    start_map.put(biaoShiHao,date);
                }
                end_map.put(biaoShiHao,date);
            }

            DknPlanItem dknPlanItem=new DknPlanItem();
            dknPlanItem.setPlanItemJson(item.toJSONString());
            dknPlanItem.setDate(date);
            dknPlanItem.setSort(i);
            dknPlanItem.setMainId(dknMainPlan.getId());
            dknPlanItem.setAddDate(DateKit.dateFormat(date+" 00:00:00"));
            dknPlanItem.setBiaoShiNos(String.join("~",start_map.keySet()));
            dknPlanItemService.saveOrUpdate(dknPlanItem);

            Integer ing=null;
            if(arr1.size()>1){
                if(arr1.size()==left_arr.size()){
                    plan_map.put(date,1);
                    ing=1;
                }else{
                    plan_map.put(date,0);
                    ing=0;
                }
            }
            if(ing==null||UtilValidate.isNotEmpty(ing)&&ing==0){
                if(arr2.size()>1){
                    if(arr2.size()==left_arr.size()){
                        plan_map.put(date,1);
                    }else{
                        plan_map.put(date,0);
                    }
                }
            }
        }

        for (String orderNo : orderNoList) {
            DknItemPlan dknItemPlan=new DknItemPlan();
            dknItemPlan.setMainId(dknMainPlan.getId());
            dknItemPlan.setBiaoShiNo(orderNo);

            String startDate_str=start_map.get(orderNo);
            if(plan_map.containsKey(startDate_str)){
                Integer i = plan_map.get(startDate_str);
                dknItemPlan.setSchedule(i);
            }
            Date startDate = DateKit.dateFormat(startDate_str + " 00:00:00");
            String endDate_str=end_map.get(orderNo);
            dknItemPlan.setStartTime(startDate);
            Date endDate = DateKit.dateFormat(endDate_str + " 00:00:00");
            dknItemPlan.setEndTime(endDate);
            dknItemPlanService.save(dknItemPlan);
        }
        return dknMainPlan.getId();
    }
}
